import { useUserStore } from '@/stores/counter'
import { createRouter, createWebHistory } from 'vue-router'


const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path:'/',
      component: () => import ('@/views/layout/LayoutContainer.vue'),
      redirect:'/chat',
      children:[
        {
          path:'/setting',
          component: () => import ('@/views/user/Setting.vue')
        },
        {
          path: '/message',
          component: () => import ('@/views/message/Message.vue')
        },
        {
          path: '/chat',
          component: () => import ('@/views/chat/chat.vue')
        },
        {
          path: '/newFriend',
          component: () => import ('@/views/contacts/NewFriend.vue')
        }
      ]
    },
    {
      path: '/login',
      component: () => import ('@/views/login/Login.vue')
    }
  ],
})

// 登录访问拦截 => 默认是直接放行的
// 根据返回值决定，是放行还是拦截
// 返回值：
// 1. undefined / true  直接放行
// 2. false 拦回from的地址页面
// 3. 具体路径 或 路径对象  拦截到对应的地址
//    '/login'   { name: 'login' }
router.beforeEach((to) => {
  // 如果没有token, 且访问的是非登录页，拦截到登录，其他情况正常放行
  const useStore = useUserStore()
  if (!useStore.accessToken && to.path !== '/login') return '/login'
})

export default router
